<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask + Vue 登录演示</title>
    <!-- 引入 Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- 引入 Axios 用于发送请求 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body { font-family: sans-serif; padding: 20px; background-color: #f0f2f5; }
        .container { max-width: 400px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        input { width: 90%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; }
        button { width: 100%; padding: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #45a049; }
        button.logout { background-color: #f44336; margin-top: 10px; }
        .error { color: red; font-size: 14px; text-align: center; }
        .success { color: green; font-size: 14px; text-align: center; }
        .tabs { display: flex; justify-content: space-around; margin-bottom: 20px; }
        .tabs span { cursor: pointer; padding-bottom: 5px; }
        .active-tab { border-bottom: 2px solid #4CAF50; font-weight: bold; }
    </style>
</head>
<body>

<div id="app" class="container">
    <h2 style="text-align: center;">Flask 系统演示</h2>

    <!-- 未登录状态显示 -->
    <div v-if="!token">
        <div class="tabs">
            <span :class="{ 'active-tab': isLoginMode }" @click="isLoginMode = true">登录</span>
            <span :class="{ 'active-tab': !isLoginMode }" @click="isLoginMode = false">注册</span>
        </div>

        <input type="text" v-model="form.username" placeholder="用户名">
        <input type="password" v-model="form.password" placeholder="密码">
        
        <button @click="submitForm">{{ isLoginMode ? '登录' : '注册' }}</button>
        <p v-if="message" :class="isError ? 'error' : 'success'">{{ message }}</p>
    </div>

    <!-- 登录后显示 -->
    <div v-else>
        <h3>欢迎你, {{ currentUser }}</h3>
        <p>你的 Token 已保存。现在尝试获取只有登录后才能看到的数据：</p>
        
        <button @click="getProtectedData">获取机密数据</button>
        
        <div v-if="secretData" style="background: #e8f5e9; padding: 10px; margin-top: 10px; border-radius: 4px;">
            <strong>服务器回应:</strong> {{ secretData }}
        </div>

        <button class="logout" @click="logout">退出登录</button>
    </div>
</div>

<script>
    const { createApp, ref } = Vue;

    createApp({
        setup() {
            const token = ref(localStorage.getItem('access_token') || '');
            const currentUser = ref(localStorage.getItem('username') || '');
            const isLoginMode = ref(true);
            const form = ref({ username: '', password: '' });
            const message = ref('');
            const isError = ref(false);
            const secretData = ref('');

            const api = axios.create({
                baseURL: 'http://127.0.0.1:5000/api'
            });

            const submitForm = async () => {
                message.value = '';
                const endpoint = isLoginMode.value ? '/login' : '/register';
                
                try {
                    const res = await api.post(endpoint, form.value);
                    
                    if (isLoginMode.value) {
                        // 登录成功逻辑
                        token.value = res.data.access_token;
                        currentUser.value = res.data.user.username;
                        // 保存到本地存储
                        localStorage.setItem('access_token', token.value);
                        localStorage.setItem('username', currentUser.value);
                        isError.value = false;
                    } else {
                        // 注册成功逻辑
                        message.value = '注册成功！请切换到登录页登录。';
                        isError.value = false;
                        isLoginMode.value = true;
                    }
                } catch (err) {
                    isError.value = true;
                    message.value = err.response?.data?.msg || '请求失败';
                }
            };

            const getProtectedData = async () => {
                try {
                    // 请求时在 Header 中带上 Token
                    const res = await api.get('/protected', {
                        headers: { Authorization: `Bearer ${token.value}` }
                    });
                    secretData.value = res.data.msg + ' ' + res.data.secret_data;
                } catch (err) {
                    alert('Token 可能过期了，请重新登录');
                    logout();
                }
            };

            const logout = () => {
                token.value = '';
                currentUser.value = '';
                secretData.value = '';
                form.value = { username: '', password: '' };
                localStorage.removeItem('access_token');
                localStorage.removeItem('username');
            };

            return {
                token, currentUser, isLoginMode, form, message, isError, secretData,
                submitForm, getProtectedData, logout
            };
        }
    }).mount('#app');
</script>

</body>
</html>